<template>
  <div class="detail-container">
    <el-card class="detail-card">
      <!-- 返回按钮 -->
      <div class="back-header">
        <el-button link type="primary" @click="handleBack" class="back-button">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
      </div>

      <!-- 详情标题 -->
      <div class="detail-header">
        <h2>菌物药详细信息 - {{ strainData.strain_number }}</h2>
      </div>

      <!-- 详细信息表格 -->
      <div class="detail-table">
        <el-table
            :data="displayData"
            border
            style="width: 100%"
            :show-header="false"
        >
          <el-table-column prop="label" width="200" align="left" />
          <el-table-column prop="value" align="left">
            <template #default="{ row }">
              <!-- 图片字段特殊处理 -->
              <div v-if="isImageField(row.label)" class="image-field">
                <div v-if="!row.value || row.value === 'null' || row.value === '无'" class="no-image">
                  无
                </div>
                <el-image
                    v-else
                    :src="getFullImageUrl(row.value)"
                    :alt="row.label"
                    fit="cover"
                    class="strain-image"
                    :preview-src-list="[getFullImageUrl(row.value)]"
                    :preview-teleported="true"
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><Picture /></el-icon>
                      <span>图片加载失败</span>
                    </div>
                  </template>
                </el-image>
              </div>
              <!-- 其他字段正常显示 -->
              <span v-else-if="isItalicField(row.label)" style="font-style: italic;">
                {{ row.value || '无' }}
              </span>
              <span v-else>
                {{ row.value || '无' }}
              </span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ArrowLeft, Picture } from '@element-plus/icons-vue';

const route = useRoute();
const router = useRouter();

// 菌物药数据接口
interface MedicinalStrainData {
  strain_number: string | null;
  medicinal_material_name: string | null;
  strain_name: string | null;
  genus_name: string | null;
  species_name: string | null;
  source: string | null;
  alias: string | null;
  resource_distribution: string | null;
  growth_environment: string | null;
  resource_situation: string | null;
  reference_sequence: string | null;
  collection_and_processing: string | null;
  chemical_composition: string | null;
  main_function: string | null;
  toxicity: string | null;
  fungal_medicine_image: string | null;
  fruiting_body_image: string | null;
  mycelium_image: string | null;
  microscopic_features_image: string | null;
}

// 显示数据接口
interface DisplayItem {
  label: string;
  value: string | null;
  key: string;
}

// 菌物药数据
const strainData = ref<MedicinalStrainData>({
  strain_number: null,
  medicinal_material_name: null,
  strain_name: null,
  genus_name: null,
  species_name: null,
  source: null,
  alias: null,
  resource_distribution: null,
  growth_environment: null,
  resource_situation: null,
  reference_sequence: null,
  collection_and_processing: null,
  chemical_composition: null,
  main_function: null,
  toxicity: null,
  fungal_medicine_image: null,
  fruiting_body_image: null,
  mycelium_image: null,
  microscopic_features_image: null,
});

// 搜索表单数据
const searchForm = ref<any>({});

// 字段映射
const fieldLabels: { [key: string]: string } = {
  strain_number: '菌株编号',
  medicinal_material_name: '药材名称',
  strain_name: '菌株拉丁名',
  genus_name: '属名',
  species_name: '种名',
  source: '来源',
  alias: '别名',
  resource_distribution: '资源分布',
  growth_environment: '生长环境',
  resource_situation: '资源情况',
  reference_sequence: '参考ITS序列GenBank收录号',
  collection_and_processing: '采收加工',
  chemical_composition: '化学成分',
  main_function: '功能主治',
  toxicity: '毒性',
  fungal_medicine_image: '菌物药图片',
  fruiting_body_image: '菌株子实体图片',
  mycelium_image: '菌丝体图片',
  microscopic_features_image: '显微特征图片',
};

// 需要斜体显示的字段
const italicFields = ['strain_name', 'genus_name', 'species_name'];

// 图片字段
const imageFields = ['菌物药图片', '菌株子实体图片', '菌丝体图片', '显微特征图片'];

// 判断字段是否需要斜体显示
const isItalicField = (label: string) => {
  const fieldKey = Object.keys(fieldLabels).find(key => fieldLabels[key] === label);
  return fieldKey ? italicFields.includes(fieldKey) : false;
};

// 判断字段是否为图片字段
const isImageField = (label: string) => {
  return imageFields.includes(label);
};

// 获取完整的图片URL
const getFullImageUrl = (imagePath: string | null) => {
  if (!imagePath) return '';
  // 如果已经是完整URL，直接返回
  if (imagePath.startsWith('http')) {
    return imagePath;
  }
  // 添加前缀
  return `http://111.160.49.98:60/Species${imagePath}`;
};

// 计算显示数据
const displayData = computed(() => {
  const data: DisplayItem[] = [];

  Object.keys(fieldLabels).forEach(key => {
    data.push({
      label: fieldLabels[key],
      value: strainData.value[key as keyof MedicinalStrainData],
      key: key
    });
  });

  return data;
});

// 返回按钮处理
const handleBack = () => {
  // 将搜索表单数据传递回搜索页面
  router.push({
    path: '/search/FungiSearch', // 根据你的实际路由路径调整
    query: {
      returnSearchForm: JSON.stringify(searchForm.value)
    }
  });
};

// 组件挂载时解析路由参数
onMounted(() => {
  try {
    // 解析菌物药数据
    if (route.query.strainData) {
      strainData.value = JSON.parse(route.query.strainData as string);
    }

    // 解析搜索表单数据
    if (route.query.searchForm) {
      searchForm.value = JSON.parse(route.query.searchForm as string);
    }
  } catch (error) {
    console.error('解析路由参数失败:', error);
    // 如果解析失败，返回搜索页面
    router.push('/search/FungiSearch');
  }
});
</script>

<style scoped>
.detail-container {
  margin: 0 20px 20px 20px;
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
  border-radius: 8px;
}

.detail-card {
  width: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.back-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.back-button {
  font-size: 16px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.detail-header {
  margin-bottom: 30px;
  text-align: center;
}

.detail-header h2 {
  color: #303133;
  font-size: 24px;
  margin: 0;
}

.detail-table {
  margin-top: 20px;
}

/* 移除表头相关样式，因为表头已隐藏 */
:deep(.el-table th) {
  display: none;
}

/* 第一列内容左对齐 */
:deep(.el-table .el-table__cell:first-child .cell) {
  text-align: left;
  padding-left: 16px;
  font-weight: 500;
  color: #303133;
}

/* 第二列内容左对齐 */
:deep(.el-table .el-table__cell:nth-child(2) .cell) {
  text-align: left;
  padding-left: 16px;
}

:deep(.el-table .el-table__cell) {
  padding: 12px 0;
}

:deep(.el-table .cell) {
  word-break: break-word;
}

/* 图片字段样式 */
.image-field {
  display: flex;
  align-items: center;
  min-height: 60px;
}

.no-image {
  color: #999;
  font-style: italic;
}

.strain-image {
  width: 120px;
  height: 120px;
  border-radius: 6px;
  border: 1px solid #e0e0e0;
  cursor: pointer;
  transition: all 0.3s ease;
}

.strain-image:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  color: #999;
  font-size: 12px;
}

.image-error .el-icon {
  font-size: 24px;
  margin-bottom: 4px;
}

/* 图片预览样式 */
:deep(.el-image-viewer__wrapper) {
  z-index: 9999;
}

:deep(.el-image-viewer__btn) {
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
}

:deep(.el-image-viewer__btn:hover) {
  background-color: rgba(0, 0, 0, 0.7);
}
</style>